package com.focusai.efairy.business.update;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.view.View;
import android.widget.Toast;

import com.focusai.efairy.R;
import com.focusai.efairy.config.AppDirFileUtil;
import com.focusai.efairy.model.file.FileInfo;
import com.focusai.efairy.model.file.FilePreviewModel;
import com.focusai.efairy.model.manager.CacheManager;
import com.focusai.efairy.model.request.GetCheckAppUpdateRequest;
import com.focusai.efairy.model.response.AppUpdateResponse;
import com.focusai.efairy.network.HttpManager;
import com.focusai.efairy.network.Response;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.utils.FileUtils;

import java.io.File;

public class AppUpdateAgent {
    public static int checkAppUpdate(final Activity activity, final boolean isUserCheck) {
        String pkgName = activity.getPackageName(); // 应用包名
        int versionCode;
        try {
            PackageInfo packageInfo = activity.getPackageManager().getPackageInfo(pkgName, 0);
            File file = new File(getAppfilePath(packageInfo.versionName));
            if (file.exists()) {
                file.delete();
            }
            versionCode = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            versionCode = 0;
        }
        GetCheckAppUpdateRequest request = new GetCheckAppUpdateRequest(versionCode + "", new Response.Listener<AppUpdateResponse>() {
            @Override
            protected void onSuccess(AppUpdateResponse response) {
                if (response != null && response.efairyandroidversion_is_update == 1) {
                    final String url = response.efairyandroidversion_update_url;
                    final String versionName = response.efairyandroidversion_code + "";
                    if (!isUserCheck && CacheManager.getIsgoreVersion() == response.efairyandroidversion_code){
                        return;
                    }
                    final UpdateDialog appUpdateDialog = new UpdateDialog(activity, R.style.custom_dialog_no_title, response.efairyandroidversion_code, new UpdateDialog.MyDialogListener() {
                        @Override
                        public void onClick(View view, boolean check) {
                            if (check)
                                return;
                            switch (view.getId()) {
                                case R.id.confirm_btn:
//                                    downLoadApp(activity, response.getDownloadUrl(), response.getVersionName(), response.getVersionCode(), Integer.valueOf(response.getPackageSize()));
                                    downLoadFile(activity, url, versionName);
                                    break;
                                case R.id.cancle_btn:

                                    break;
                                default:
                                    break;
                            }
                        }
                    }, response.efairyandroidversion_update_force == 1);
                    appUpdateDialog.setTvUpdateInfo(response.efairyandroidversion_update_content);
                    appUpdateDialog.setUpdateVersion(response.efairyandroidversion_code + "");
                    appUpdateDialog.show();
                } else {
                    if (isUserCheck) {
                        Toast.makeText(activity, R.string.common_not_new_version, Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            protected void onFail(NetworkException exception) {

            }
        });

        HttpManager.getInstance().sendRequest(request);
        return versionCode;
    }

    private static void downLoadFile(final Activity activity, String url, final String versionName) {
        final FileInfo fileInfo = new FileInfo();
        fileInfo.downLoadUrl = url;
        FilePreviewModel filePreviewModel = new FilePreviewModel(new FilePreviewModel.IPreviewCallback() {
            @Override
            public void onFileDetailGet(FileInfo fileDetail) {

            }

            @Override
            public void onBeforeDownFile() {
                AppUpdateNotification.getInstance(activity).updateDownloadProgress(0);

            }

            @Override
            public void onDownLoadFileSuccess() {
                AppUpdateNotification.getInstance(activity).cancelNotification();
                FileUtils.renameDowloadedFile(FileUtils.getKdFileTmpPath(fileInfo), getAppfilePath(versionName));
                openFile(activity, new File(getAppfilePath(versionName)));
            }

            @Override
            public void onDownLoadFileFailed() {
                AppUpdateNotification.getInstance(activity).cancelNotification();
                Toast.makeText(activity, "请检查网络,安装包更新失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDownLoadFileProcess(int percent) {
                AppUpdateNotification.getInstance(activity).updateDownloadProgress(percent);
            }
        });
        filePreviewModel.downLoadFile(fileInfo);
    }

    /**
     * 打开文件，现用于下载完打开APK程序
     */
    public static void openFile(Context context, File file) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    private static String getAppfilePath(String versioName) {
        return AppDirFileUtil.getLogDirPath() + "efairy_" + versioName + ".apk";
    }
}
